package com.xxwy.lifecycle.initialization;

import com.xxwy.lifecycle.bean.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.TimeUnit;

/**
 * 初始化.
 * - 前置回调
 *    - BeanPostProcessor#postProcessBeforeInitialization
 *        - applicationContext中有默认加的初始化，有一些aware回调，bean对象的set
 * - 初始化
 * - 初始化后置
 * @author xxwy
 * @date 2021/7/23 0023
 */
public class BeanInitializationLifeCycleDemo {

    public static void main(String[] args) throws InterruptedException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/dependency-lookup-context.xml");
        // 无效，生命周期已经启动
        // applicationContext.getBeanFactory().addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        // so 除了在除了一开始的时候就注册BeanProcessor, 还可以写回调add, 如下
        applicationContext.addBeanFactoryPostProcessor(beanFactory -> {
            beanFactory.addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        });
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user);

        //去掉引用，销毁,
        applicationContext.getBeanFactory().destroySingletons();
        user = null;
        System.gc();

        TimeUnit.SECONDS.sleep(3L);
    }

}